import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getMyNotificationList,
  getMyNotificationDetail,
  markNotificationAsRead,
  markAllNotificationsAsRead
} from '@/api/notifications'

export interface Notification {
  id: string
  title: string
  message: string
  content: string
  type: 'info' | 'warn' | 'error' | 'success'
  is_read: boolean
  read: boolean
  pushed_at?: string
  created_at?: string
  updated_at?: string
  timestamp?: string
}

interface Pagination {
  page: number
  pageSize: number
  total: number
}

interface Filters {
  type: string
  unread: boolean
}

export const useNotificationStore = defineStore('notification', () => {
  const notifications = ref<Notification[]>([])
  const unreadCount = ref(0)
  const loading = ref(false)
  const pagination = ref<Pagination>({
    page: 1,
    pageSize: 10,
    total: 0
  })
  const filters = ref<Filters>({
    type: '',
    unread: false
  })

  /**
   * 获取未读通知总数
   */
  const fetchUnreadCount = async (): Promise<number> => {
    try {
      const res = await getMyNotificationList({ page: 1, pageSize: 1, unread: true })
      if (res.code === 200 && res.data) {
        unreadCount.value = res.data.total || 0
        return unreadCount.value
      }
    } catch (error) {
      console.error('获取未读数量失败:', error)
      // 如果获取失败，尝试从本地列表统计
      unreadCount.value = notifications.value.filter(n => !n.is_read).length
    }
    return unreadCount.value
  }

  /**
   * 获取通知列表
   * @param params 查询参数
   * @param append 是否追加到现有列表（用于分页加载更多）
   */
  const fetchNotifications = async (params: Record<string, any> = {}, append = false): Promise<Notification[] | undefined> => {
    loading.value = true
    try {
      const queryParams: Record<string, any> = {
        page: params.page || pagination.value.page,
        pageSize: params.pageSize || pagination.value.pageSize,
        ...filters.value,
        ...params
      }

      // 如果 filters 中有空字符串，移除该字段
      if (queryParams.type === '') {
        delete queryParams.type
      }

      const res = await getMyNotificationList(queryParams)

      if (res.code === 200 && res.data) {
        const list = res.data.list || []
        
        // 转换数据格式，统一字段名
        const formattedList: Notification[] = list.map((item: any) => ({
          id: item.id,
          title: item.title,
          message: item.content,
          content: item.content,
          type: item.type || 'info',
          is_read: item.is_read || false,
          read: item.is_read || false, // 兼容旧字段名
          pushed_at: item.pushed_at,
          created_at: item.created_at,
          updated_at: item.updated_at,
          timestamp: item.pushed_at || item.created_at
        }))

        if (append) {
          notifications.value.push(...formattedList)
        } else {
          notifications.value = formattedList
        }

        pagination.value = {
          page: res.data.page || queryParams.page,
          pageSize: res.data.pageSize || queryParams.pageSize,
          total: res.data.total || 0
        }

        // 如果查询的是全部通知（不是仅未读），更新未读数量
        // 通过统计本地列表中的未读数量来更新
        if (!queryParams.unread) {
          unreadCount.value = notifications.value.filter(n => !n.is_read).length
        } else {
          // 如果查询的是仅未读，使用总数作为未读数量
          unreadCount.value = pagination.value.total
        }

        return formattedList
      }
    } catch (error) {
      console.error('获取通知列表失败:', error)
      ElMessage.error('获取通知列表失败')
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取通知详情
   * @param id 通知ID
   */
  const fetchNotificationDetail = async (id: string): Promise<Notification | undefined> => {
    try {
      const res = await getMyNotificationDetail({ id })

      if (res.code === 200 && res.data) {
        // 转换数据格式
        const item = res.data
        return {
          id: item.id,
          title: item.title,
          message: item.content,
          content: item.content,
          type: item.type || 'info',
          is_read: item.is_read || false,
          read: item.is_read || false,
          pushed_at: item.pushed_at,
          created_at: item.created_at,
          updated_at: item.updated_at,
          timestamp: item.pushed_at || item.created_at
        }
      }
    } catch (error) {
      console.error('获取通知详情失败:', error)
      ElMessage.error('获取通知详情失败')
      throw error
    }
  }

  /**
   * 标记通知为已读
   * @param id 通知ID
   */
  const markAsRead = async (id: string): Promise<void> => {
    const notification = notifications.value.find(n => n.id === id)
    if (notification && !notification.is_read) {
      try {
        const res = await markNotificationAsRead({ id })

        if (res.code === 200) {
          notification.is_read = true
          notification.read = true
          // 更新未读数量：减少1，或重新获取未读数量
          unreadCount.value = Math.max(0, unreadCount.value - 1)
          // 也可以选择重新获取未读数量以确保准确性
          // await fetchUnreadCount()
        }
      } catch (error) {
        console.error('标记已读失败:', error)
        // 即使API失败，也更新本地状态（乐观更新）
        notification.is_read = true
        notification.read = true
        unreadCount.value = Math.max(0, unreadCount.value - 1)
      }
    }
  }

  /**
   * 标记所有通知为已读
   */
  const markAllAsRead = async (): Promise<void> => {
    try {
      const res = await markAllNotificationsAsRead()

      if (res.code === 200) {
        notifications.value.forEach(n => {
          n.is_read = true
          n.read = true
        })
        unreadCount.value = 0
        ElMessage.success('已标记所有通知为已读')
      }
    } catch (error) {
      console.error('标记全部已读失败:', error)
      ElMessage.error('标记全部已读失败')
    }
  }

  /**
   * 移除通知（仅本地操作，不调用API）
   * @param id 通知ID
   */
  const removeNotification = (id: string): void => {
    const index = notifications.value.findIndex(n => n.id === id)
    if (index > -1) {
      const notification = notifications.value[index]
      if (!notification.is_read) {
        unreadCount.value = Math.max(0, unreadCount.value - 1)
      }
      notifications.value.splice(index, 1)
    }
  }

  /**
   * 清空所有通知（仅本地操作）
   */
  const clearAll = (): void => {
    notifications.value = []
    unreadCount.value = 0
  }

  /**
   * 设置筛选条件
   * @param newFilters 新的筛选条件
   */
  const setFilters = (newFilters: Partial<Filters>): void => {
    filters.value = { ...filters.value, ...newFilters }
  }

  /**
   * 刷新通知列表
   */
  const refresh = (): Promise<Notification[] | undefined> => {
    pagination.value.page = 1
    return fetchNotifications({ page: 1 }, false)
  }

  /**
   * 加载更多通知（分页）
   */
  const loadMore = (): Promise<Notification[] | undefined> => {
    if (pagination.value.page * pagination.value.pageSize >= pagination.value.total) {
      return Promise.resolve([])
    }
    pagination.value.page += 1
    return fetchNotifications({ page: pagination.value.page }, true)
  }

  return {
    notifications,
    unreadCount,
    loading,
    pagination,
    filters,
    fetchUnreadCount,
    fetchNotifications,
    fetchNotificationDetail,
    markAsRead,
    markAllAsRead,
    removeNotification,
    clearAll,
    setFilters,
    refresh,
    loadMore
  }
})

